package com.mindskip.xzs.service.impl;

import com.github.pagehelper.ISelect;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mindskip.xzs.domain.dto.ExamPaperQuestionItemObject;
import com.mindskip.xzs.domain.dto.ExamPaperTitleItemObject;
import com.mindskip.xzs.domain.dto.admin.exampaperanswer.ExamPaperAnswerPageDTO;
import com.mindskip.xzs.domain.dto.student.exampaper.*;
import com.mindskip.xzs.domain.dto.student.task.TaskItemAnswerObject;
import com.mindskip.xzs.domain.vo.admin.exampaper.ExamPaperWithQuestionVO;
import com.mindskip.xzs.domain.vo.student.education.SubjectVO;
import com.mindskip.xzs.domain.vo.student.exampaper.ExamPaperAnswerItemVO;
import com.mindskip.xzs.domain.vo.student.exampaper.ExamPaperAnswerPageStudentVO;
import com.mindskip.xzs.domain.vo.student.exampaper.ExamPaperAnswerVO;
import com.mindskip.xzs.domain.vo.student.exampaper.ExamPaperReadVO;
import com.mindskip.xzs.domain.entity.*;
import com.mindskip.xzs.domain.enums.ExamPaperAnswerStatusEnum;
import com.mindskip.xzs.domain.enums.ExamPaperTypeEnum;
import com.mindskip.xzs.domain.enums.QuestionTypeEnum;
import com.mindskip.xzs.domain.vo.admin.exampaperanswer.ExamPaperAnswerPageVO;
import com.mindskip.xzs.event.CalculateExamPaperAnswerCompleteEvent;
import com.mindskip.xzs.event.UserEvent;
import com.mindskip.xzs.repository.BaseMapper;
import com.mindskip.xzs.repository.ExamPaperAnswerMapper;
import com.mindskip.xzs.repository.ExamPaperMapper;
import com.mindskip.xzs.repository.QuestionMapper;
import com.mindskip.xzs.service.*;
import com.mindskip.xzs.utility.*;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Service
public class ExamPaperAnswerServiceImpl extends BaseServiceImpl<ExamPaperAnswer> implements ExamPaperAnswerService {

    private final ExamPaperAnswerMapper examPaperAnswerMapper;

    private final SubjectService subjectService;

    private final UserService userService;

    private final ExamPaperMapper examPaperMapper;

    private final TextContentService textContentService;

    private final QuestionMapper questionMapper;

    private final ApplicationEventPublisher eventPublisher;

    private final ExamPaperService examPaperService;

    private final TaskExamCustomerAnswerService taskExamCustomerAnswerService;

    private final ExamPaperQuestionCustomerAnswerService examPaperQuestionCustomerAnswerService;

    public ExamPaperAnswerServiceImpl(BaseMapper<ExamPaperAnswer> baseMapper, ExamPaperAnswerMapper examPaperAnswerMapper, SubjectService subjectService, UserService userService, ExamPaperMapper examPaperMapper, TextContentService textContentService, QuestionMapper questionMapper, ApplicationEventPublisher eventPublisher, ExamPaperService examPaperService, TaskExamCustomerAnswerService taskExamCustomerAnswerService, ExamPaperQuestionCustomerAnswerService examPaperQuestionCustomerAnswerService) {
        super(baseMapper);
        this.examPaperAnswerMapper = examPaperAnswerMapper;
        this.subjectService = subjectService;
        this.userService = userService;
        this.examPaperMapper = examPaperMapper;
        this.textContentService = textContentService;
        this.questionMapper = questionMapper;
        this.eventPublisher = eventPublisher;
        this.examPaperService = examPaperService;
        this.taskExamCustomerAnswerService = taskExamCustomerAnswerService;
        this.examPaperQuestionCustomerAnswerService = examPaperQuestionCustomerAnswerService;
    }

    // 得到答卷总数
    @Override
    public Integer selectAllCount() {
        return examPaperAnswerMapper.selectAllCount();
    }

    @Override
    public PageInfo<ExamPaperAnswerPageVO> getExamPaperAnswerByPage(ExamPaperAnswerPageDTO examPaperAnswerPageDTO) {

        PageHelper.startPage(examPaperAnswerPageDTO.getPageIndex(), examPaperAnswerPageDTO.getPageSize(), "id desc");
        List<ExamPaperAnswer> examPaperAnswerList = examPaperAnswerMapper.selectByPage(examPaperAnswerPageDTO);
        PageInfo<ExamPaperAnswer> oldPageInfo = new PageInfo<>(examPaperAnswerList);

        List<ExamPaperAnswerPageVO> examPaperAnswerPageVOList = examPaperAnswerList
                .stream()
                .map(examPaperAnswer -> {
                    ExamPaperAnswerPageVO examPaperAnswerPageVO = BeanCopyUtils.copyBean(examPaperAnswer, ExamPaperAnswerPageVO.class);

                    examPaperAnswerPageVO.setCreateTime(DateTimeUtil.dateFormat(examPaperAnswer.getCreateTime()));

                    examPaperAnswerPageVO.setUserScore(ExamUtil.scoreToString(examPaperAnswer.getUserScore()));

                    Subject subject = subjectService.selectById(examPaperAnswer.getSubjectId());
                    examPaperAnswerPageVO.setSubjectName(subject.getName());

                    examPaperAnswerPageVO.setPaperScore(ExamUtil.scoreToString(examPaperAnswer.getPaperScore()));

                    examPaperAnswerPageVO.setDoTime(ExamUtil.secondToString(examPaperAnswer.getDoTime()));

                    examPaperAnswerPageVO.setSystemScore(ExamUtil.scoreToString(examPaperAnswer.getSystemScore()));

                    User user = userService.selectById(examPaperAnswer.getCreateUser());
                    examPaperAnswerPageVO.setUserName(user.getUserName());

                    return examPaperAnswerPageVO;
                })
                .collect(Collectors.toList());

        return PageInfoUtil.copyMap(oldPageInfo, examPaperAnswerPageVOList);
    }

    @Override
    public String answerSubmit(ExamPaperSubmitDTO examPaperSubmitDTO, User user) {

        // 计算试卷提交结果(不入库)，将试卷信息存储在 ExamPaperAnswerInfo 中
        ExamPaperAnswerInfo examPaperAnswerInfo = calculateExamPaperAnswer(examPaperSubmitDTO, user);
        if (null == examPaperAnswerInfo) {
            throw new RuntimeException("试卷不能重复做");
        }

        ExamPaperAnswer examPaperAnswer = examPaperAnswerInfo.getExamPaperAnswer();
        Integer userScore = examPaperAnswer.getUserScore();
        String score = ExamUtil.scoreToString(userScore);
        UserEventLog userEventLog = new UserEventLog(user.getId(), user.getUserName(), user.getRealName(), new Date());
        String content = user.getUserName() + " 提交试卷：" + examPaperAnswerInfo.getExamPaper().getName()
                + " 得分：" + score
                + " 耗时：" + ExamUtil.secondToString(examPaperAnswer.getDoTime());
        userEventLog.setContent(content);
        eventPublisher.publishEvent(new UserEvent(userEventLog));

        // 用户提交的试卷答案进行入库
        eventPublisher.publishEvent(new CalculateExamPaperAnswerCompleteEvent(examPaperAnswerInfo));

        return score;
    }

    @Override
    public ExamPaperReadVO read(Integer id) {

        ExamPaperReadVO examPaperReadVO = new ExamPaperReadVO();

        // 给 ExamPaperReadVO 中的 paper 属性赋值
        ExamPaperAnswer examPaperAnswer = examPaperAnswerMapper.selectByPrimaryKey(id);
        ExamPaperWithQuestionVO examPaperWithQuestion = examPaperService.getExamPaperWithQuestion(examPaperAnswer.getExamPaperId());
        examPaperReadVO.setPaper(examPaperWithQuestion);

        // 给 ExamPaperReadVO 中的 answer 属性赋值
        ExamPaperAnswerVO examPaperAnswerVO = examPaperAnswerToExamPaperAnswerVO(examPaperAnswer);
        examPaperReadVO.setAnswer(examPaperAnswerVO);

        return examPaperReadVO;
    }

    public ExamPaperAnswerVO examPaperAnswerToExamPaperAnswerVO(ExamPaperAnswer examPaperAnswer) {

        ExamPaperAnswerVO examPaperAnswerVO = BeanCopyUtils.copyBean(examPaperAnswer, ExamPaperAnswerVO.class);

        examPaperAnswerVO.setScore(ExamUtil.scoreToString(examPaperAnswer.getUserScore()));

        List<ExamPaperQuestionCustomerAnswer> examPaperQuestionCustomerAnswers = examPaperQuestionCustomerAnswerService
                .getExamPaperQuestionCustomerAnswerByExamPaperAnswerId(examPaperAnswer.getId());

        List<ExamPaperAnswerItemVO> examPaperAnswerItemVOS = examPaperQuestionCustomerAnswers.stream()
                .map(new Function<ExamPaperQuestionCustomerAnswer, ExamPaperAnswerItemVO>() {
                    @Override
                    public ExamPaperAnswerItemVO apply(ExamPaperQuestionCustomerAnswer examPaperQuestionCustomerAnswer) {

                        return examPaperQuestionCustomerAnswerService.examPaperQuestionCustomerAnswerToExamPaperAnswerItemVO(examPaperQuestionCustomerAnswer);
                    }
                })
                .collect(Collectors.toList());

        examPaperAnswerVO.setAnswerItems(examPaperAnswerItemVOS);
        return examPaperAnswerVO;
    }

    // 计算试卷提交结果(不入库)
    public ExamPaperAnswerInfo calculateExamPaperAnswer(ExamPaperSubmitDTO examPaperSubmitDTO, User user) {

        ExamPaperAnswerInfo examPaperAnswerInfo = new ExamPaperAnswerInfo();
        Date now = new Date();
        ExamPaper examPaper = examPaperMapper.selectByPrimaryKey(examPaperSubmitDTO.getId());
        ExamPaperTypeEnum paperTypeEnum = ExamPaperTypeEnum.fromCode(examPaper.getPaperType());
        //任务试卷只能做一次
        if (paperTypeEnum == ExamPaperTypeEnum.Task) {
            // 根据试卷id和用户id得到用户相对应的试卷答案
            ExamPaperAnswer examPaperAnswer = examPaperAnswerMapper.selectByPaperIdAndUserId(examPaperSubmitDTO.getId(), user.getId());
            if (null != examPaperAnswer)
                return null;
        }
        // 得到该试卷所对应的文本内容，文本内容为该试卷所有的题目
        String content = textContentService.selectById(examPaper.getFrameTextContentId()).getContent();
        // 将文本内容转化为 ExamPaperTitleItemObject 对象
        List<ExamPaperTitleItemObject> examPaperTitleItemObjects = JsonUtil.toJsonListObject(content, ExamPaperTitleItemObject.class);
        if (ObjectUtils.isEmpty(examPaperTitleItemObjects)) {
            throw new RuntimeException("试卷所对应的文本内容为空");
        }
        // 得到该试卷所对应的所有题目id
        List<Integer> questionIds = examPaperTitleItemObjects.stream()
                .flatMap(new Function<ExamPaperTitleItemObject, Stream<Integer>>() {
                    @Override
                    public Stream<Integer> apply(ExamPaperTitleItemObject examPaperTitleItemObject) {
                        return examPaperTitleItemObject.getQuestionItems().stream()
                                .map(new Function<ExamPaperQuestionItemObject, Integer>() {
                                    @Override
                                    public Integer apply(ExamPaperQuestionItemObject examPaperQuestionItemObject) {
                                        return examPaperQuestionItemObject.getId();
                                    }
                                });
                    }
                })
                .collect(Collectors.toList());
        // 根据题目id获得该试卷所对应的所有题目
        List<Question> questions = questionMapper.selectByIds(questionIds);

        // 得到用户所完成的试卷题目答案 ExamPaperQuestionCustomerAnswer类
        List<ExamPaperQuestionCustomerAnswer> examPaperQuestionCustomerAnswers = examPaperTitleItemObjects.stream()
                .flatMap(new Function<ExamPaperTitleItemObject, Stream<ExamPaperQuestionCustomerAnswer>>() {
                    @Override
                    public Stream<ExamPaperQuestionCustomerAnswer> apply(ExamPaperTitleItemObject examPaperTitleItemObject) {
                        return examPaperTitleItemObject.getQuestionItems().stream()
                                .map(new Function<ExamPaperQuestionItemObject, ExamPaperQuestionCustomerAnswer>() {
                                    @Override
                                    public ExamPaperQuestionCustomerAnswer apply(ExamPaperQuestionItemObject examPaperQuestionItemObject) {

                                        // 根据 examPaperQuestionItemObject 中的题目Id 找到相对应的题目
                                        Question question = questions.stream()
                                            .filter(new Predicate<Question>() {
                                                @Override
                                                public boolean test(Question question) {
                                                    return question.getId().equals(examPaperQuestionItemObject.getId());
                                                }
                                            })
                                            .findFirst()
                                            .orElse(null);
                                        if (ObjectUtils.isEmpty(question)) {
                                            throw new RuntimeException("没有找到相对应的题目");
                                        }

                                        // 根据 examPaperQuestionItemObject 中的题目Id 找到用户提交的相对应的题目答案
                                        ExamPaperSubmitItemDTO customerQuestionAnswer = examPaperSubmitDTO.getAnswerItems().stream()
                                            .filter(new Predicate<ExamPaperSubmitItemDTO>() {
                                                @Override
                                                public boolean test(ExamPaperSubmitItemDTO examPaperSubmitItemDTO) {
                                                    return examPaperSubmitItemDTO.getQuestionId().equals(examPaperQuestionItemObject.getId());
                                                }
                                            })
                                            .findFirst()
                                            .orElse(null);
                                        return ExamPaperQuestionCustomerAnswerFromVM(question, customerQuestionAnswer, examPaper, examPaperQuestionItemObject.getItemOrder(), user, now);
                                    }
                                });
                    }
                })
                .collect(Collectors.toList());

        // 得到用户所完成的试卷答案 ExamPaperAnswer类
        ExamPaperAnswer examPaperAnswer = ExamPaperAnswerFromVM(examPaperSubmitDTO, examPaper, examPaperQuestionCustomerAnswers, user, now);

        // 给 examPaperAnswerInfo 的 examPaper 属性赋值
        examPaperAnswerInfo.setExamPaper(examPaper);

        // 给 examPaperAnswerInfo 的 examPaperQuestionCustomerAnswers 属性赋值
        examPaperAnswerInfo.setExamPaperQuestionCustomerAnswers(examPaperQuestionCustomerAnswers);

        // 给 examPaperAnswerInfo 的 examPaperAnswer 属性赋值
        examPaperAnswerInfo.setExamPaperAnswer(examPaperAnswer);

        return examPaperAnswerInfo;
    }

    /**
     * 用户提交答案的转化为 ExamPaperQuestionCustomerAnswer
     */
    private ExamPaperQuestionCustomerAnswer ExamPaperQuestionCustomerAnswerFromVM(Question question, ExamPaperSubmitItemDTO customerQuestionAnswer, ExamPaper examPaper, Integer itemOrder, User user, Date now) {
        ExamPaperQuestionCustomerAnswer examPaperQuestionCustomerAnswer = new ExamPaperQuestionCustomerAnswer();
        examPaperQuestionCustomerAnswer.setQuestionId(question.getId());
        examPaperQuestionCustomerAnswer.setExamPaperId(examPaper.getId());
        examPaperQuestionCustomerAnswer.setQuestionScore(question.getScore());
        examPaperQuestionCustomerAnswer.setSubjectId(examPaper.getSubjectId());
        examPaperQuestionCustomerAnswer.setItemOrder(itemOrder);
        examPaperQuestionCustomerAnswer.setCreateTime(now);
        examPaperQuestionCustomerAnswer.setCreateUser(user.getId());
        examPaperQuestionCustomerAnswer.setQuestionType(question.getQuestionType());
        examPaperQuestionCustomerAnswer.setQuestionTextContentId(question.getInfoTextContentId());
        if (null == customerQuestionAnswer) {
            examPaperQuestionCustomerAnswer.setCustomerScore(0);
        } else {
            setSpecialFromVM(examPaperQuestionCustomerAnswer, question, customerQuestionAnswer);
        }
        return examPaperQuestionCustomerAnswer;
    }

    /**
     * 判断提交答案是否正确，保留用户提交的答案
     */
    private void setSpecialFromVM(ExamPaperQuestionCustomerAnswer examPaperQuestionCustomerAnswer, Question question, ExamPaperSubmitItemDTO customerQuestionAnswer) {
        QuestionTypeEnum questionTypeEnum = QuestionTypeEnum.fromCode(examPaperQuestionCustomerAnswer.getQuestionType());
        switch (questionTypeEnum) {
            // 如果是单选题或者判断题
            case SingleChoice:
            case TrueFalse:
                examPaperQuestionCustomerAnswer.setAnswer(customerQuestionAnswer.getContent());
                examPaperQuestionCustomerAnswer.setDoRight(question.getCorrect().equals(customerQuestionAnswer.getContent()));
                examPaperQuestionCustomerAnswer.setCustomerScore(examPaperQuestionCustomerAnswer.getDoRight() ? question.getScore() : 0);
                break;
            // 如果是多选题
            case MultipleChoice:
                String customerAnswer = ExamUtil.contentToString(customerQuestionAnswer.getContentArray());
                examPaperQuestionCustomerAnswer.setAnswer(customerAnswer);
                examPaperQuestionCustomerAnswer.setDoRight(customerAnswer.equals(question.getCorrect()));
                examPaperQuestionCustomerAnswer.setCustomerScore(examPaperQuestionCustomerAnswer.getDoRight() ? question.getScore() : 0);
                break;
            // 如果是填空题
            case GapFilling:
                String correctAnswer = JsonUtil.toJsonStr(customerQuestionAnswer.getContentArray());
                examPaperQuestionCustomerAnswer.setAnswer(correctAnswer);
                examPaperQuestionCustomerAnswer.setCustomerScore(0);
                break;
            // 如果是简单题
            default:
                examPaperQuestionCustomerAnswer.setAnswer(customerQuestionAnswer.getContent());
                examPaperQuestionCustomerAnswer.setCustomerScore(0);
                break;
        }
    }

    // 用户提交的答案转换为ExamPaperAnswer
    private ExamPaperAnswer ExamPaperAnswerFromVM(ExamPaperSubmitDTO examPaperSubmitVM, ExamPaper examPaper, List<ExamPaperQuestionCustomerAnswer> examPaperQuestionCustomerAnswers, User user, Date now) {

        // 计算系统判定得分
        Integer systemScore = examPaperQuestionCustomerAnswers.stream()
                .mapToInt(ExamPaperQuestionCustomerAnswer::getCustomerScore)
                .sum();
        // 计算做对题目数量
        long questionCorrect = examPaperQuestionCustomerAnswers.stream()
                .filter(a -> a.getCustomerScore().equals(a.getQuestionScore()))
                .count();

        ExamPaperAnswer examPaperAnswer = new ExamPaperAnswer();
        examPaperAnswer.setPaperName(examPaper.getName());
        examPaperAnswer.setDoTime(examPaperSubmitVM.getDoTime());
        examPaperAnswer.setExamPaperId(examPaper.getId());
        examPaperAnswer.setCreateUser(user.getId());
        examPaperAnswer.setCreateTime(now);
        examPaperAnswer.setSubjectId(examPaper.getSubjectId());
        examPaperAnswer.setQuestionCount(examPaper.getQuestionCount());
        examPaperAnswer.setPaperScore(examPaper.getScore());
        examPaperAnswer.setPaperType(examPaper.getPaperType());
        examPaperAnswer.setSystemScore(systemScore);
        examPaperAnswer.setUserScore(systemScore);
        examPaperAnswer.setTaskExamId(examPaper.getTaskExamId());
        examPaperAnswer.setQuestionCorrect((int) questionCorrect);
        // 如果用户提交的试卷中含有填空题或者简答题则需要进行批改
        boolean needJudge = examPaperQuestionCustomerAnswers.stream()
                .anyMatch(d -> QuestionTypeEnum.needSaveTextContent(d.getQuestionType()));
        if (needJudge) {
            // 用户提交的试卷中含有填空题或者简答题
            examPaperAnswer.setStatus(ExamPaperAnswerStatusEnum.WaitJudge.getCode());
        } else {
            examPaperAnswer.setStatus(ExamPaperAnswerStatusEnum.Complete.getCode());
        }
        return examPaperAnswer;
    }

    @Override
    @Transactional
    public String edit(ExamPaperAnswerDTO examPaperAnswerDTO, User user) {

        boolean notJudge = examPaperAnswerDTO.getAnswerItems().stream()
                .anyMatch(examPaperAnswerItemDTO -> examPaperAnswerItemDTO.getDoRight() == null && examPaperAnswerItemDTO.getScore() == null);
        if (notJudge) {
            throw new RuntimeException("有未批改的题目");
        }

        ExamPaperAnswer examPaperAnswer = examPaperAnswerMapper.selectByPrimaryKey(examPaperAnswerDTO.getId());
        ExamPaperAnswerStatusEnum examPaperAnswerStatusEnum = ExamPaperAnswerStatusEnum.fromCode(examPaperAnswer.getStatus());
        if (examPaperAnswerStatusEnum == ExamPaperAnswerStatusEnum.Complete) {
            throw new RuntimeException("试卷已经完成");
        }

        String score = judge(examPaperAnswerDTO);

        UserEventLog userEventLog = new UserEventLog(user.getId(), user.getUserName(), user.getRealName(), new Date());
        String content = user.getUserName() + " 批改试卷：" + examPaperAnswer.getPaperName() + " 得分：" + score;
        userEventLog.setContent(content);
        eventPublisher.publishEvent(new UserEvent(userEventLog));

        return score;
    }

    // 对用户提交的试卷进行批改
    @Override
    @Transactional
    public String judge(ExamPaperAnswerDTO examPaperAnswerDTO) {

        ExamPaperAnswer examPaperAnswer = examPaperAnswerMapper.selectByPrimaryKey(examPaperAnswerDTO.getId());

        // 得到需批改的题目
        List<ExamPaperAnswerItemDTO> judgeItems = examPaperAnswerDTO.getAnswerItems().stream()
                .filter(examPaperAnswerItemDTO -> examPaperAnswerItemDTO.getDoRight() == null)
                .collect(Collectors.toList());

        Integer customerScore = examPaperAnswer.getUserScore();
        Integer questionCorrect = examPaperAnswer.getQuestionCorrect();
        List<ExamPaperAnswerUpdate> examPaperAnswerUpdates = new ArrayList<>(judgeItems.size());
        for (ExamPaperAnswerItemDTO d : judgeItems) {
            ExamPaperAnswerUpdate examPaperAnswerUpdate = new ExamPaperAnswerUpdate();
            examPaperAnswerUpdate.setId(d.getId());
            examPaperAnswerUpdate.setCustomerScore(ExamUtil.scoreToInteger(d.getScore()));
            boolean doRight = examPaperAnswerUpdate.getCustomerScore().equals(ExamUtil.scoreToInteger(d.getQuestionScore()));
            examPaperAnswerUpdate.setDoRight(doRight);
            examPaperAnswerUpdates.add(examPaperAnswerUpdate);
            customerScore += examPaperAnswerUpdate.getCustomerScore();
            if (examPaperAnswerUpdate.getDoRight()) {
                ++questionCorrect;
            }
        }
        examPaperAnswer.setUserScore(customerScore);
        examPaperAnswer.setQuestionCorrect(questionCorrect);
        examPaperAnswer.setStatus(ExamPaperAnswerStatusEnum.Complete.getCode());
        int i1 = examPaperAnswerMapper.updateByPrimaryKeySelective(examPaperAnswer);
        if (i1 < 0) {
            throw new RuntimeException("更新用户提交的试卷答案失败");
        }
        int i = examPaperQuestionCustomerAnswerService.updateScore(examPaperAnswerUpdates);
        if (i <= 0) {
            throw new RuntimeException("更新用户提交的题目答案失败");
        }

        ExamPaperTypeEnum examPaperTypeEnum = ExamPaperTypeEnum.fromCode(examPaperAnswer.getPaperType());
        if (examPaperTypeEnum == ExamPaperTypeEnum.Task) {
            //任务试卷批改完成后，需要更新任务的状态
            ExamPaper examPaper = examPaperMapper.selectByPrimaryKey(examPaperAnswer.getExamPaperId());
            Integer taskId = examPaper.getTaskExamId();
            Integer userId = examPaperAnswer.getCreateUser();
            TaskExamCustomerAnswer taskExamCustomerAnswer = taskExamCustomerAnswerService.getTaskExamCustomerAnswerByTaskExamIdAndUserId(taskId, userId);
            TextContent textContent = textContentService.selectById(taskExamCustomerAnswer.getTextContentId());
            List<TaskItemAnswerObject> taskItemAnswerObjects = JsonUtil.toJsonListObject(textContent.getContent(), TaskItemAnswerObject.class);
            if (ObjectUtils.isEmpty(taskItemAnswerObjects)) {
                throw new RuntimeException("用户任务表所对应的文本内容为空");
            }
            // 从用户任务表所对应的文本内容中找到用户提交的对应的任务试卷
            taskItemAnswerObjects.stream()
                    .filter(d -> d.getExamPaperAnswerId().equals(examPaperAnswer.getId()))
                    .findFirst()
                    .ifPresent(taskItemAnswerObject -> taskItemAnswerObject.setStatus(examPaperAnswer.getStatus()));
            textContentService.jsonConvertUpdate(textContent, taskItemAnswerObjects, null);
            // 将更新的TextContent写入到数据库
            textContentService.updateByIdFilter(textContent);
        }

        return ExamUtil.secondToString(customerScore);
    }

    @Override
    public PageInfo<ExamPaperAnswerPageStudentVO> page(ExamPaperAnswerPageStudentDTO examPaperPageDTO, User user) {

        PageInfo<ExamPaperAnswer> oldPageInfo = PageHelper.startPage(examPaperPageDTO.getPageIndex(), examPaperPageDTO.getPageSize(), "id desc")
                .doSelectPageInfo(() -> examPaperAnswerMapper.selectByPageStudent(examPaperPageDTO));

        List<SubjectVO> subjectVOs = subjectService.getSubjectVOByLevel(user.getUserLevel());

        List<ExamPaperAnswerPageStudentVO> examPaperAnswerPageStudentVOS = oldPageInfo.getList().stream()
                .map(examPaperAnswer -> {
                    ExamPaperAnswerPageStudentVO examPaperAnswerPageStudentVO = BeanCopyUtils.copyBean(examPaperAnswer, ExamPaperAnswerPageStudentVO.class);
                    examPaperAnswerPageStudentVO.setCreateTime(DateTimeUtil.dateFormat(examPaperAnswer.getCreateTime()));
                    examPaperAnswerPageStudentVO.setUserScore(ExamUtil.scoreToString(examPaperAnswer.getUserScore()));

                    SubjectVO subjectVO = subjectVOs.stream()
                            .filter(subjectVO1 -> subjectVO1.getId().equals(examPaperAnswer.getSubjectId()))
                            .findFirst()
                            .orElse(null);
                    if (ObjectUtils.isEmpty(subjectVO)) {
                        throw new RuntimeException("没有找到对应的学科");
                    }
                    examPaperAnswerPageStudentVO.setSubjectName(subjectVO.getName());
                    examPaperAnswerPageStudentVO.setPaperScore(ExamUtil.scoreToString(examPaperAnswer.getPaperScore()));
                    examPaperAnswerPageStudentVO.setDoTime(ExamUtil.secondToString(examPaperAnswer.getDoTime()));
                    examPaperAnswerPageStudentVO.setSystemScore(ExamUtil.scoreToString(examPaperAnswer.getSystemScore()));
                    examPaperAnswerPageStudentVO.setUserName(user.getUserName());
                    return examPaperAnswerPageStudentVO;
                })
                .collect(Collectors.toList());

        return PageInfoUtil.copyMap(oldPageInfo, examPaperAnswerPageStudentVOS);
    }
}
